package algorithm.sort;

import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;

/**
 * 桶排序
 */
public class BucketSort {

    private static int[] arr = new int[10];

    @Before
    public void init() {
        for (int i = 0, j = arr.length; i < j; i++) {
            arr[i] = (int) (Math.random() * 1000);
        }
    }

    @Test
    public void sort() {
        System.out.println("排序前：" + Arrays.toString(arr));
        int n = arr.length;
        int bask[][] = new int[10][n];
        int index[] = new int[10];
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            max = Math.max(max, (Integer.toString(arr[i]).length()));
        }
        String str;
        for (int i = max - 1; i >= 0; i--) {
            for (int j = 0; j < n; j++) {
                str = "";
                if (Integer.toString(arr[j]).length() < max) {
                    for (int k = 0; k < max - Integer.toString(arr[j]).length(); k++)
                        str += "0";
                }
                str += Integer.toString(arr[j]);
                bask[str.charAt(i) - '0'][index[str.charAt(i) - '0']++] = arr[j];
            }
            int pos = 0;
            for (int j = 0; j < 10; j++) {
                for (int k = 0; k < index[j]; k++) {
                    arr[pos++] = bask[j][k];
                }
            }
            for (int x = 0; x < 10; x++) {
                index[x] = 0;
            }
        }
        System.out.println("排序后：" + Arrays.toString(arr));
    }
}
